//
//  HttpTool.swift
//  WeiBo
//
//  Created by Tony on 2018/1/6.
//  Copyright © 2018年 Tony. All rights reserved.
//

import UIKit
import AFNetworking


// Swift三种定义枚举的方法
enum requestType: String {
    case GET = "GET"
    case POST = "POST"
}

enum requestType2: NSInteger {
    case GET = 1
    case POST = 2
}

enum requestType3 {
    case GET
    case POST
}

class HttpTool: NSObject {
    /*
     Swift要两种形式单例
     1、通过某个接口返回单例
     2、通过构造函数或类方法都返回单例
     */
    
    // 创建一个单例
    static let shareInstance: HttpTool = {
        let tool = HttpTool.init()
        return tool
    }()
}


// MARK: GET/POST
extension HttpTool {
    func request(request: requestType, urlStr: String, parametes: [String:AnyObject]?, finished:@escaping (_ result: AnyObject?, _ error: Error?)->(Void)) {
        
        let mgr: AFHTTPSessionManager = AFHTTPSessionManager()
        mgr.responseSerializer.acceptableContentTypes?.insert("text/html")
        mgr.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // 成功的回调
        let success = { (task: URLSessionDataTask, result: Any?) in

            finished(result as AnyObject?,nil)
            
        }
        
        // 失败回调
        let failure = { (task: URLSessionDataTask?, error: Error) in
            finished(nil,error)
        }
        
        // GET
        if request == .GET {
            
            mgr.get(urlStr, parameters: parametes, progress: nil, success: success, failure: failure)
        }
        
        // POST
        if request == .POST {
            mgr.post(urlStr, parameters: parametes, progress: nil, success: success, failure: failure)
        }
    }
}

// MARK: -请求token
extension HttpTool {
    func loadAccessToken(code: String, finish: @escaping (_ result: AnyObject?, _ error: Error?) -> (Void)) {
        
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 2.获取请求的参数
        let parameters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "redirect_uri" : redirect_uri, "code" : code]
        
        request(request: .POST, urlStr: urlString, parametes: parameters as [String : AnyObject]?) { (result: AnyObject?, error: Error?) -> (Void) in
            
            // 回调
            finish(result,error)
        }
    }
}

// MARK: -请求用户信息
extension HttpTool {
    func loadUserInfo(access_token: String, uid: String, finish: @escaping (_ result: AnyObject?, _ error: Error?)->(Void)) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token" : access_token, "uid" : uid]
        
        request(request: .GET, urlStr: urlStr, parametes: parameters as [String : AnyObject]?) { (result: AnyObject?, error: Error?) -> (Void) in
            
            finish(result,error)
        }
    }
}

// MARK:-请求首页数据
extension HttpTool {
    func loadStatuses(finish: @escaping (_ result: [[String : AnyObject]]?, _ error: Error? )->(Void)) {
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters = ["access_token" : UserAccoutViewModel.shareInstance.accout?.access_token]
        
        request(request: .GET, urlStr: urlStr, parametes: parameters as [String : AnyObject]?) { (result: AnyObject?, error: Error?) -> (Void) in

            
            guard let resultDict = result as! [String : AnyObject]? else {
                let err = NSError.init(domain: "resultDict解析出错", code: -100, userInfo: nil)
                finish(nil,err)
                return
            }
            
            guard let statusArr = resultDict["statuses"] else {
                let err = NSError.init(domain: "statusArr解析出错", code: -100, userInfo: nil)
                finish(nil,err)
                return;
            }
            
            finish(statusArr as? [[String : AnyObject]],nil)

        }
    }
}


/*
extension NetworkTools {
    func loadUserInfo(access_token : String, uid : String, finished : (result : [String : AnyObject]?, error : NSError?) -> ()) {
        // 1.获取请求的URLString
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 2.获取请求的参数
        let parameters = ["access_token" : access_token, "uid" : uid]
        
        // 3.发送网络请求
        request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
            finished(result: result as? [String : AnyObject] , error: error)
        }
    }
}
*/







// 常用如下两种地址来测试网络请求
// http://httpbin.org/get
// http://httpbin.org/post

/*
 HttpTool.shareInstance.request(urlStr: "http://httpbin.org/get", parametes: ["name" : "Tony" as AnyObject]) { (result: AnyObject?, error:Error?) -> (Void) in
 
     if error != nil {
         mySelfLog(error)
         return
     }
 
 mySelfLog(result)
 }
 */

/*
 HttpTool.shareInstance.request(request: .POST, urlStr: "http://httpbin.org/post", parametes: ["name" : "Tony" as AnyObject]) { (result: AnyObject?, error: Error?) -> (Void) in
 
     if error != nil {
         return
     }
 
     mySelfLog(result)
 
 }
 */

